<?php
/* SVN FILE: $Id: championships_controller.php 324 2010-07-16 11:58:32Z gregory.rome $ */
/**
 * Championships Controller.
 *
 * @todo Add file description.
 *
 * cBBweb : Digital Blood Bowl league interface (http://code.google.com/p/cbbweb/)
 * Copyright 2009-2010, Grégory Romé.
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2009-2010, Grégory Romé.
 * @link          http://code.google.com/p/cbbweb/ cBBweb Project
 * @package       cbbweb
 * @subpackage    cbbweb.controllers
 * @version       $Revision: 324 $
 * @modifiedby    $LastChangedBy: gregory.rome $
 * @lastmodified  $Date: 2010-07-16 11:58:32 +0000 (Fri, 16 Jul 2010) $
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */
/**
 * Championships Controller.
 *
 * @todo Add class description.
 *
 * @package       cbbweb
 * @subpackage    cbbweb.controllers
 */
class ChampionshipsController extends AppController {
	var $name = 'Championships';
	var $paginate = array (
		'Championship' => array (
			'contain' => array (
				'RuleType' => array (
					'LocalizedString'
				),
				'Team'
			)
		)
	);

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function index() {
		$championships = $this->paginate('Championship');
		if (isset ($this->params['requested'])) {
			return $championships;
		} else {
			$this->set('championships', $championships);
		}
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Championship', true));
			$this->redirect(array (
				'action' => 'index'
			));
		}
		$championship = $this->Championship->find('first', array(
			'conditions' => array('Championship.ID' => $id),
			'contain' => array(
				'RuleType' => array ('LocalizedString'),
				'Team' => array('fields' => array('Team.ID'))
			)
		));

		foreach ($championship['Team'] as $team) {
			$conditions[] = $team['ID'];
		}
		unset($championship['Team']);
		$this->set('championship', $championship);

		$this->paginate['TeamRanking'] = array(
			'order' => array(
				'TeamRanking.iGroup' => 'asc',
				'TeamRanking.iRanking' => 'asc'),
			'contain' => array (
				'Team' => array(
					'Coach',
					'Race' => array (
						'LocalizedString'
					)
		)));

		if (isset ($conditions)) {
			$teams = $this->paginate('TeamRanking', array (
				array (
				'Team.ID' => $conditions,
				'TeamRanking.idRule_Listing' => $championship['Championship']['ID']
				)
			));

			$this->set('teams', $teams);
		}
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function add() {
		if (!empty ($this->data['Championship'])) {
			$file = $this->data['Championship']['tmpFile'];
			if (!$this->isUploadedFile($file)) {
				$this->Session->setFlash(__('Upload failed', true));
			} else {
				rename($file['tmp_name'], '/tmp/last_tmp.sqlite');
				$ret = $this->_updateFromTemp($this->data['Championship']);
				if ($ret) {
					$this->Session->setFlash(__('The Championship has been saved', true));
					$this->redirect(array('action'=>'index'));
				} else {
					$this->Session->setFlash(__('The Championship could not be saved. Please, try again.', true));
				}
			}
		}
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function update() {
		if (!$this->championship) {
			$this->Session->setFlash(__('You must select a championship', true));
			$this->set('noview', true);
			return;
		} else {
			$this->set('noview', false);
			App :: import('Model', 'Championship');
			$Championship = new Championship();
			$Championship->recursive = -1;
			$championship = $Championship->read(null, $this->championship);
			$this->set('championship', $championship);
		}

		if (!empty ($this->data['Championship'])) {
			$file = $this->data['Championship']['tmpFile'];
			if (!$this->isUploadedFile($file)) {
				$this->Session->setFlash(__('Upload failed', true));
			} else {
				rename($file['tmp_name'], '/tmp/last_tmp.sqlite');

				$ret = $this->_updateFromTemp($championship);
				if ($ret) {
					$this->Session->setFlash(__('The Championship has been updated', true));
					$this->redirect(array('action'=>'index'));
				} else {
					$this->Session->setFlash(__('The Championship could not be updated. Please, try again.', true));
				}
			}
		}
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function _updateFromTemp($currentChampionship)
	{
		if( !isset($currentChampionship['Championship']['ID']) )
		{
			$this->Championship->changeDataSource('temp');
			$this->Championship->recursive = -1;
			$championship = $this->Championship->find('first');
			$this->Championship->changeDataSource('default');

			$championship['Championship']['strName'] = $this->data['Championship']['strName'];
			unset ($championship['Championship']['ID']);
			$championship['Championship']['iSeason'] = 1;

			$ret = $this->Championship->save($championship);
			if(!$ret) { return $ret; }
			$championship['Championship']['ID'] = $this->Championship->getId();

			$this->Championship->TeamRanking->changeDataSource('temp');
			$this->Championship->TeamRanking->recursive = -1;
			$teamRankings = $this->Championship->TeamRanking->find('all');
			$this->Championship->TeamRanking->changeDataSource('default');

			foreach ($teamRankings as $teamRanking) {
				$this->Championship->TeamRanking->create();
				unset($teamRanking['TeamRanking']['ID']);
				$teamRanking['TeamRanking']['idRule_Listing'] = $championship['Championship']['ID'];
				$teamRanking['TeamRanking']['idRule_Types'] = $championship['Championship']['idRule_Types'];
				$teamRanking['TeamRanking']['iSeason'] = $championship['Championship']['iSeason'];
				$ret = $this->Championship->TeamRanking->save($teamRanking);
				if(!$ret) { return $ret; }
			}
		} else
		{
			$championship = $currentChampionship;

			$this->Championship->TeamRanking->changeDataSource('temp');
			$this->Championship->TeamRanking->recursive = -1;
			$teamRankings = $this->Championship->TeamRanking->find('all');
			$this->Championship->TeamRanking->changeDataSource('default');
			foreach ($teamRankings as $teamRanking) {
				$result = $this->Championship->TeamRanking->find('first', array(
					'conditions' => array(
						'TeamRanking.idRule_Listing' => $championship['Championship']['ID'],
						'TeamRanking.iSeason' => $championship['Championship']['iSeason'],
						'TeamRanking.idTeam_Listing' => $teamRanking['TeamRanking']['idTeam_Listing']
					)
				));
				$teamRanking['TeamRanking']['ID'] = $result['TeamRanking']['ID'];
				unset($teamRanking['TeamRanking']['idRule_Listing']);
				unset($teamRanking['TeamRanking']['idRule_Types']);
				unset($teamRanking['TeamRanking']['iSeason']);
				$ret = $this->Championship->TeamRanking->save($teamRanking);
				if(!$ret) { return $ret; }
			}
		}

		/* ------------------------------------------------------------------ */
		/* Calendars */
		$this->Championship->Calendar->changeDataSource('temp');
		$this->Championship->Calendar->recursive = -1;
		$calendars = $this->Championship->Calendar->find('all');
		$this->Championship->Calendar->changeDataSource('default');

		foreach ($calendars as &$calendar) {

			$this->Championship->Calendar->recursive = -1;
			$result = $this->Championship->Calendar->find('first', array(
				'conditions' => array(
					'Calendar.idRule_Listing' => $championship['Championship']['ID'],
					'Calendar.idTeam_Listing_Away' => $calendar['Calendar']['idTeam_Listing_Away'],
					'Calendar.idTeam_Listing_Home' => $calendar['Calendar']['idTeam_Listing_Home'],
					'Calendar.Championship_iSeason' => $calendar['Calendar']['Championship_iSeason'],
					'Calendar.Championship_iDay' => $calendar['Calendar']['Championship_iDay']),
				'fields' => array('Calendar.ID')
			));

			if($result) {
				$calendar['Calendar']['ID'] = $result['Calendar']['ID'];
				$this->Championship->Calendar->save($calendar);
			} else {
				unset ($calendar['Calendar']['ID']);
				if($calendar['Calendar']['bPlayed'] == 0) {
					unset($calendar['Calendar']['Away_iScore']);
					unset($calendar['Calendar']['Home_iScore']);
				}
				$calendar['Calendar']['idRule_Listing'] = $championship['Championship']['ID'];
				$this->Championship->Calendar->create();
				$this->Championship->Calendar->save($calendar);
			}
		}

		/* ------------------------------------------------------------------ */
		/* Teams */
		$this->Championship->Team->changeDataSource('temp');
		$this->Championship->Team->StatisticsTeam->changeDataSource('temp');

		$teams = $this->Championship->Team->find('all', array(
			'contain' => array(
				'StatisticsTeam',
				'StatisticsSeasonTeam' => array(
					'conditions' => array('OR' => array(
						'StatisticsSeasonTeam.iSeason' => -1,
						'StatisticsSeasonTeam.bFinished' => 0))
				)
			)
		));

		$this->Championship->Team->changeDataSource('default');
		$this->Championship->Team->StatisticsTeam->changeDataSource('default');

		$this->Championship->TeamRanking->changeDataSource('temp');
		foreach ($teams as &$team) {
			$this->_saveTeam($team, $championship);
		}

		/* ------------------------------------------------------------------ */
		/* Players */
		$this->Championship->Team->Player->changeDataSource('temp');
		$this->Championship->Team->Player->StatisticsPlayer->changeDataSource('temp');
		$this->Championship->Team->Player->PlayerSkill->changeDataSource('temp');

		$players = $this->Championship->Team->Player->find('all', array(
			'contain' => array(
				'StatisticsPlayer',
				'StatisticsSeasonPlayer' => array(
					'conditions' => array('OR' => array(
						'StatisticsSeasonPlayer.iSeason' => -1,
						'StatisticsSeasonPlayer.bFinished' => 0))
				),
				'PlayerSkill'
			)
		));

		$this->Championship->Team->Player->changeDataSource('default');
		$this->Championship->Team->Player->StatisticsPlayer->changeDataSource('default');
		$this->Championship->Team->Player->PlayerSkill->changeDataSource('default');

		foreach ($players as $player) {
			$this->_savePlayer($player, $championship);
		}

		return true;
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function edit($id = null) {

		if (!$id && empty ($this->data)) {
			$this->Session->setFlash(__('Invalid Championship', true));
			$this->redirect(array (
				'action' => 'index'
			));
		}

		if (!empty ($this->data)) {
			if ($this->Championship->save($this->data)) {
				$this->Session->setFlash(__('The Championship has been saved', true));
				$this->redirect(array ('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The Championship could not be saved. Please, try again.', true));
			}
		}
		if (empty ($this->data)) {
			$this->data = $this->Championship->read(null, $id);
		}
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function delete($id = null) {

		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Championship', true));
			$this->redirect(array ('action' => 'index'));
		}

		if ($this->Championship->delete($id)) {
			$this->Session->setFlash(__('Championship deleted', true));
			$this->redirect(array ('action' => 'index'));
		}

		$this->Session->setFlash(__('The Championship could not be deleted. Please, try again.', true));
		$this->redirect(array ('action' => 'index'));
	}

	function new_season($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Championship', true));
			$this->redirect(array ('action' => 'index'));
		} else {
			$this->redirect(array ('action' => 'view', 'id' => $id));
		}
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function _saveTeam($team, $championship)
	{
		$result = $this->Championship->Team->find('first',array(
			'conditions' => array('Team.ID' => $team['Team']['ID'])
		));
		if(!$result) {
			$this->Championship->Team->create();
			$this->Championship->Team->save($team);
		}
		/* ------------------------------------------------------------------ */
		/* StatisticsTeam */
		if(!empty($team['StatisticsTeam']['ID'])) {
			$result = $this->Championship->Team->StatisticsTeam->find('first', array(
				'fields' => array('StatisticsTeam.ID'),
				'conditions' => array('StatisticsTeam.idTeam_Listing' => $team['Team']['ID']),
			));
			if(!$result) {
				unset($team['StatisticsTeam']['ID']);
			} else {
				$team['StatisticsTeam']['ID'] = $result['StatisticsTeam']['ID'];
				unset($result);
			}

			if(empty($team['StatisticsSeasonTeam']))
			{
				$new = true;

				$team['StatisticsSeasonTeam'][0] = $team['StatisticsTeam'];
				unset($team['StatisticsSeasonTeam'][0]['ID']);
				$team['StatisticsSeasonTeam'][0]['idRule_Listing'] = -1;
				$team['StatisticsSeasonTeam'][0]['iSeason'] = -1;
				$team['StatisticsSeasonTeam'][0]['bFinished'] = 1;

				$team['StatisticsSeasonTeam'][1] = $team['StatisticsTeam'];
				unset($team['StatisticsSeasonTeam'][1]['ID']);
				$team['StatisticsSeasonTeam'][1]['idRule_Listing'] = $championship['Championship']['ID'];
				$team['StatisticsSeasonTeam'][1]['iSeason'] = $championship['Championship']['iSeason'];
				$team['StatisticsSeasonTeam'][1]['bFinished'] = 0;

				$ref = &$team['StatisticsSeasonTeam'][0];
				$stats = &$team['StatisticsSeasonTeam'][1];
			} else
			{
				$new = false;

				if($team['StatisticsSeasonTeam'][0]['bFinished'] == 1)
				{
					$ref = &$team['StatisticsSeasonTeam'][0];
					$stats = &$team['StatisticsSeasonTeam'][1];
				} else {
					$ref = &$team['StatisticsSeasonTeam'][1];
					$stats = &$team['StatisticsSeasonTeam'][0];
				}
			}
			$this->_updateSeasonStats(&$stats, $team['StatisticsTeam'], $ref, $new);
		} else {
			unset($team['StatisticsTeam']);
		}
		$ret = $this->Championship->Team->saveAll($team);
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function _updateSeasonStats(&$seasonStats, $stats, $refStats, $new=false) {
		foreach ( $stats as $key => $value ) {
			switch ( $key ) {
				case 'ID':
				case 'idTeam_Listing':
				case 'idPlayer_Listing':
				case 'idRule_Listing':
				case 'iSeason':
				case 'bFinished':
					break;
				case 'iBestMatchRating':
					if(!$new){
						$seasonStats[$key] = $stats[$key] > $refStats[$key] ? $stats[$key] : $refStats[$key];
					} else {
						$seasonStats[$key] = 0;
					}
					break;
				case 'Average_iMatchRating':
				case 'Average_iSpectators':
				case 'Average_iCashEarned':
					if(!$new){
						$seasonStats[$key] = ($stats['iMatchPlayed']*$stats[$key] - $refStats['iMatchPlayed']*$refStats[$key]) / ($stats['iMatchPlayed'] - $refStats['iMatchPlayed']);
					} else {
						$seasonStats[$key] = 0;
					}
					break;
				case 'iPossessionBall':
				case 'Occupation_iOwn':
				case 'Occupation_iTheir':
					$seasonStats[$key] = 0;
					break;
				default:
					$seasonStats[$key] = $stats[$key] - $refStats[$key];
					break;
			}
		}
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function _createStatsSkillsPlayers( $players ) {
		foreach($players as &$player) {
			unset($player['StatisticsPlayer']['ID']);
			foreach($player['PlayerSkill'] as &$playerSkill) {
				unset($playerSkill['ID']);
			}

			$this->Championship->Team->Player->StatisticsPlayer->create();
			$tmp['StatisticsPlayer'] = $player['StatisticsPlayer'];
			$this->Championship->Team->Player->StatisticsPlayer->save($tmp);
			unset($tmp);

			$statisticsSeasonPlayer[0] = $player['StatisticsPlayer'];
			$statisticsSeasonPlayer[0]['bFinished'] = 1;
			$statisticsSeasonPlayer[0]['iSeason'] = -1;
			unset($statisticsSeasonPlayer[0]['ID']);

			$statisticsSeasonPlayer[1] = $player['StatisticsPlayer'];
			$statisticsSeasonPlayer[1]['iSeason'] = $championship['Championship']['iSeason'];
			$statisticsSeasonPlayer[1]['idRule_Listing'] = $championship['Championship']['ID'];
			$statisticsSeasonPlayer[1]['bFinished'] = 0;
			unset($statisticsSeasonPlayer[1]['ID']);

			$this->_updateSeasonStats(&$statisticsSeasonPlayer[1],
				$statisticsSeasonPlayer[0], $statisticsSeasonPlayer[0]);

			$this->Championship->Team->Player->StatisticsSeasonPlayer->saveAll($tmp);

			$this->Championship->Team->Player->PlayerSkill->create();
			$this->Championship->Team->Player->PlayerSkill->saveAll($player['PlayerSkill']);
	}
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function _savePlayer($player, $championship, $new=false)
	{
		$statisticsPlayer = &$player['StatisticsPlayer'];

		$result = $this->Championship->Team->Player->find('first',array(
			'conditions' => array('Player.ID' => $player['Player']['ID'])
		));
		if(!$result) {
			$this->Championship->Team->Player->create();
			$this->Championship->Team->Player->save($player);
		}

		if(!empty($statisticsPlayer['ID'])) {
			$result = $this->Championship->Team->Player->StatisticsPlayer->find('first',
				array(
					'fields' => array('StatisticsPlayer.ID'),
					'conditions' => array('StatisticsPlayer.idPlayer_Listing' => $player['Player']['ID'])
			));

			if(!$result) {
				unset($statisticsPlayer['ID']);
				$player['StatisticsSeasonPlayer'][0] = $statisticsPlayer;
				$player['StatisticsSeasonPlayer'][1] = $statisticsPlayer;

				$player['StatisticsSeasonPlayer'][0]['bFinished'] = 1;
				$player['StatisticsSeasonPlayer'][0]['iSeason'] = -1;
				$player['StatisticsSeasonPlayer'][0]['idRule_Listing'] = -1;

				$player['StatisticsSeasonPlayer'][1]['bFinished'] = 0;
				$player['StatisticsSeasonPlayer'][1]['iSeason'] = $championship['Championship']['iSeason'];
				$player['StatisticsSeasonPlayer'][1]['idRule_Listing'] = $championship['Championship']['ID'];

				$refs = &$player['StatisticsSeasonPlayer'][0];
				$stats = &$player['StatisticsSeasonPlayer'][1];
			} else if($new) {

			} else {
				$statisticsPlayer['ID'] = $result['StatisticsPlayer']['ID'];

				if(empty($player['StatisticsSeasonPlayer']))
				{
					$player['StatisticsSeasonPlayer'][0] = $statisticsPlayer;
					$player['StatisticsSeasonPlayer'][1] = $statisticsPlayer;
					$refs = &$player['StatisticsSeasonPlayer'][0];
					$stats = &$player['StatisticsSeasonPlayer'][1];
				} else
				{
					if($player['StatisticsSeasonPlayer'][0]['iSeason'] == -1) {
						$refs = &$player['StatisticsSeasonPlayer'][0];
						$stats = &$player['StatisticsSeasonPlayer'][1];
					} else {
						$refs = &$player['StatisticsSeasonPlayer'][1];
						$stats = &$player['StatisticsSeasonPlayer'][0];
					}
				}
			}
			unset($result);
			$this->_updateSeasonStats(&$stats, $player['StatisticsPlayer'], $refs);
		}

		foreach($player['PlayerSkill'] as &$playerSkill) {
			$result = $this->Championship->Team->Player->PlayerSkill->find('first',
				array(
				'conditions' => array(
					'PlayerSkill.idPlayer_Listing' => $playerSkill['idPlayer_Listing'],
					'PlayerSkill.idSkill_Listing' => $playerSkill['idSkill_Listing']
				)
			));
			if(!$result) {
				unset($playerSkill['ID']);
			} else {
				$playerSkill['ID'] = $result['PlayerSkill']['ID'];
			}

			$ret = $this->Championship->Team->Player->saveAll($player);
			return $ret;
		}
	}
}
?>